package top.lingkang.fv.springmvc;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import top.lingkang.finalvalidated.core.FinalValidator;

/**
 * @author lingkang
 * created by 2025-11-10
 */
@Slf4j
public class FinalValidatorSpringMvcConfig {

    /**
     * FinalValidatorFactorySpring 内置 FinalValidatorFactory ，用于折中调用。
     * 主要目的是让FinalValidatorFactory能够脱离spring框架使用
     */
    @Bean
    public FinalValidatorFactorySpringMvc finalValidatorFactorySpringMvc(@Autowired RequestMappingHandlerAdapter adapter) {
        ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer();
        if (initializer == null) {
            throw new RuntimeException("WebBindingInitializer not found");
        }
        FinalValidatorFactorySpringMvc finalValidatorFactory = new FinalValidatorFactorySpringMvc();
        initializer.setValidator(finalValidatorFactory);
        // init ...
        FinalValidator.factory = finalValidatorFactory;
        FinalValidator.init();
/*
        // 加载提示
        Resource resource = resourceLoader.getResource("classpath:defaultValidated.properties");
        InputStreamReader reader = new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8);
        FinalValidatorFactory.message.load(reader);
        FinalValidatorUtils.close(reader);

        // 加载自定义的
        resource = resourceLoader.getResource("classpath:finalValidated.properties");
        if (resource.exists()) {
            reader = new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8);
            Properties finalValidated = new Properties();
            finalValidated.load(reader);
            // 覆盖原有默认的
            FinalValidatorFactory.message.putAll(finalValidated);
            FinalValidatorUtils.close(reader);
        }*/

        log.info("final-validator-spring-web Initialization completed");
        return finalValidatorFactory;
    }


}
